package com.lixixi.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixixi.tingshu.common.constant.KafkaConstant;
import com.lixixi.tingshu.common.constant.RedisConstant;
import com.lixixi.tingshu.common.util.AuthContextHolder;
import com.lixixi.tingshu.model.user.UserInfo;
import com.lixixi.tingshu.user.mapper.UserInfoMapper;
import com.lixixi.tingshu.user.service.WxMiniAppService;
import com.lixixi.tingshu.vo.user.UserInfoVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class WxMiniAppServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements WxMiniAppService {
	@Autowired
	WxMaService wxMaService;

	@Autowired
	KafkaTemplate<String, String> kafkaTemplate;

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	@Override
	public JSONObject wxLogin(String jsCode) throws WxErrorException {
		//向wx小程序登录服务发起请求
		WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(jsCode);
		//获取用户唯一标识
		String openid = sessionInfo.getOpenid();
		//获取会话密钥
		String sessionKey = sessionInfo.getSessionKey();
		//根据用户id查询是否第一次登录
		UserInfo userInfo = this.getOne(new LambdaUpdateWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
		if (ObjectUtil.isEmpty(userInfo))
		{
			//首次登录注册
			userInfo = new UserInfo();
			userInfo.setNickname("听友" + System.currentTimeMillis());
			userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
			userInfo.setWxOpenId(openid);
			this.save(userInfo);
			//TODO:保存成功id回填,后续配合消息队列注册用户账户
			kafkaTemplate.send(KafkaConstant.QUEUE_USER_REGISTER, userInfo.getId().toString());
		}
		//设置缓存
		redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + sessionKey
				, JSONObject.toJSONString(userInfo)
				, RedisConstant.USER_LOGIN_KEY_TIMEOUT
				, TimeUnit.SECONDS);
		//返回会话密钥session值
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token", sessionKey);
		return jsonObject;
	}

	@Override
	public void updateUser(UserInfoVo userInfoVo) {
		//获取当前用户id
		Long userId = AuthContextHolder.getUserId();
		LambdaUpdateWrapper<UserInfo> userInfoLambdaUpdateWrapper = new LambdaUpdateWrapper<UserInfo>()
				.set(!StringUtils.isEmpty(userInfoVo.getNickname()), UserInfo::getNickname, userInfoVo.getNickname())
				.set(!StringUtils.isEmpty(userInfoVo.getAvatarUrl()),UserInfo::getAvatarUrl, userInfoVo.getAvatarUrl())
				.eq(UserInfo::getId, userId);
		//更新用户信息
		update(userInfoLambdaUpdateWrapper);
	}
}
